package cn.com.sina.finance.todolist.base;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import java.util.List;

/**
 * @author yuebo
 * @date 2022/5/23
 */
public class SimpleTabAdapter extends FragmentPagerAdapter {

    protected FragmentManager fragmentManager;
    protected List<Tab> tabList;

    public SimpleTabAdapter(@NonNull FragmentManager fm, List<Tab> tabList) {
        super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.fragmentManager = fm;
        this.tabList = tabList;
    }

    public SimpleTabAdapter(@NonNull FragmentManager fm, int behavior, List<Tab> tabList) {
        super(fm, behavior);
        this.fragmentManager = fm;
        this.tabList = tabList;
    }

    public List<Tab> getTabList() {
        return tabList;
    }

    public void setTabList(List<Tab> tabList) {
        this.tabList = tabList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return tabList.get(position).getFragment();
    }

    @Override
    public int getCount() {
        return tabList == null ? 0 : tabList.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return tabList.get(position).getTitle();
    }

    /**
     * 清除Fragment
     *
     * @param viewPager
     */
    public void clearFragment(ViewPager viewPager) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < getCount(); i++) {
            long itemId = getItemId(i);
            String name = makeFragmentName(viewPager.getId(), itemId);
            Fragment fragment = fragmentManager.findFragmentByTag(name);
            if (fragment != null) {
                transaction.remove(fragment);
            }
        }
        transaction.commitNowAllowingStateLoss();
    }

    /**
     * 同FragmentPagerAdapter源码makeFragmentName()方法
     *
     * @param viewId
     * @param id
     * @return
     */
    public static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }
}
